package com.zg.scf.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.dao.BaseEntity;
import com.zg.common.core.dao.scf.ImgConfigDao;
import com.zg.common.core.dao.scf.entity.ImgCategory;
import com.zg.common.core.dao.scf.entity.ImgCondition;
import com.zg.common.core.dao.scf.entity.ImgConfig;
import com.zg.common.core.service.PageBaseService;
import com.zg.scf.domain.req.img.ImgConditionAddReq;
import com.zg.scf.domain.req.img.ImgConfigAddReq;
import com.zg.scf.domain.req.img.ImgConfigCategoryAddReq;
import com.zg.scf.domain.vo.ImgCategoryVo;
import com.zg.scf.domain.vo.ImgConditionVo;
import com.zg.scf.domain.vo.ImgConfigVo;
import com.zg.scf.feign.ThirdFeign;
import com.zg.scf.service.CompanyService;
import com.zg.scf.service.ImgCategoryService;
import com.zg.scf.service.ImgConditionService;
import com.zg.scf.service.ImgConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/5/22 10:47
 */



@Service
@Slf4j
public class ImgConfigServiceImpl extends PageBaseService<ImgConfig, ImgConfigDao> implements ImgConfigService {

    @Resource
    private ImgCategoryService imgCategoryService;

    @Resource
    private ImgConditionService imgConditionService;

    @Resource
    private ThirdFeign thirdFeign;

    @Resource
    private CompanyService companyService;


    public ImgConfigVo getInfoByCompanyId(Long companyId){
        ImgConfig source = new ImgConfig();
        source.setCompanyId(companyId);
        ImgConfigVo imgConfigVo = getConfigVo(source);
        return  imgConfigVo;
    }
    @Override
    public ImgConfigVo getInfo(Long id){
        //ImgConfig source = new ImgConfig();
        ImgConfig source= getById( id);
        ImgConfigVo imgConfigVo = getConfigVo(source);
        return  imgConfigVo;
    }

    private ImgConfigVo getConfigVo(ImgConfig imgConfig){
        //取到大类别
        List<ImgCategory> pCategoryList = imgCategoryService.listByConfigId(imgConfig.getId());

        List<ImgCategory> subList = imgCategoryService.listByPids(pCategoryList.stream().map(t->t.getId()).collect(Collectors.toList()));

        ImgCondition imgCondition = new ImgCondition();
        imgCondition.setCategoryIds(subList.stream().map(BaseEntity::getId).collect(Collectors.toList()));
        List<ImgCondition> conditions = imgConditionService.list(imgCondition);

        // 将条件按分类ID分组
        Map<Long, List<ImgCondition>> conditionMap = conditions.stream()
                .collect(Collectors.groupingBy(ImgCondition::getCategoryId));

        //List<ImgCategory> pCategoryList = categories.stream().filter(t->t.getPid().equals(0L)).collect(Collectors.toList());
        //List<ImgCategory> allSubCategoryList = categories.stream().filter(t->!t.getPid().equals(0L)).collect(Collectors.toList());

        Map<Long,List<ImgCategory>> allSubCategoryMap = subList.stream().collect(Collectors.groupingBy(ImgCategory::getPid));

        ImgConfigVo configVo = new ImgConfigVo();
        BeanUtils.copyProperties(imgConfig, configVo);
        List<ImgCategoryVo> pCategoryVoList = new ArrayList<>();
        // 组装最终结果

        for(ImgCategory pCategory : pCategoryList){
            ImgCategoryVo  pCategoryVo = new ImgCategoryVo();
            BeanUtils.copyProperties(pCategory, pCategoryVo);

            List<ImgCategory>  subCategoryList =allSubCategoryMap.getOrDefault(pCategory.getId(), new ArrayList<>());
            List<ImgCategoryVo> subCategoryVoList = new ArrayList<>();
            for (ImgCategory category : subCategoryList) {
                ImgCategoryVo categoryVo = new ImgCategoryVo();

                BeanUtils.copyProperties(category, categoryVo);

                // 获取该分类下的所有条件
                List<ImgCondition> categoryConditions = conditionMap.getOrDefault(category.getId(), new ArrayList<>());
                List<ImgConditionVo> conditionVos = categoryConditions.stream().map(condition -> {
                    ImgConditionVo conditionVo = new ImgConditionVo();
                    BeanUtils.copyProperties(condition, conditionVo);

                    return conditionVo;
                }).collect(Collectors.toList());
                categoryVo.setConditionList(conditionVos);
                subCategoryVoList.add(categoryVo);
            }
            pCategoryVo.setSubList(subCategoryVoList);
            pCategoryVoList.add(pCategoryVo);
        }
        configVo.setCategoryList(pCategoryVoList);
        return configVo;
    }

    @Transactional
    @Override
    public void addCondition(ImgConfigAddReq addReq) {
        //removeAll();
        removeCondition();

        ImgConfig imgConfig = getById(addReq.getId());

        baseDao.saveOrUpdate(imgConfig);

        List<ImgConfigCategoryAddReq> categoryAddReqList = addReq.getCategoryList();

        for(int i=0;i<categoryAddReqList.size();i++){
            ImgConfigCategoryAddReq categoryAddReq = categoryAddReqList.get(i);
//            ImgCategory imgCategory = new ImgCategory();
//            BeanUtils.copyProperties(categoryAddReq, imgCategory);
//            imgCategory.setConfigId(imgConfig.getId());
//            //imgCategoryService.add(imgCategory);

            List<ImgConfigCategoryAddReq> subCategoryList = categoryAddReq.getSubList();

            for(int j=0;j<subCategoryList.size();j++){
                ImgConfigCategoryAddReq subCategoryAddReq = subCategoryList.get(j);
                ImgCategory subCategory = imgCategoryService.getById(subCategoryAddReq.getId());
                BeanUtils.copyProperties(subCategoryAddReq, subCategory);
                imgCategoryService.edit(subCategory);

                List<ImgConditionAddReq> conditions = subCategoryAddReq.getConditionList();
                for(int k=0;k<conditions.size();k++){
                    ImgConditionAddReq conditionAddReq = conditions.get(k);
                    ImgCondition condition = new ImgCondition();
                    BeanUtils.copyProperties(conditionAddReq, condition);
                    condition.setCategoryId(subCategoryAddReq.getId());
                    imgConditionService.add(condition);
                }
            }
        }
    }

    @Transactional
    @Override
    public void add(ImgConfigAddReq addReq) {
        //removeAll();
        removeCondition();

        ImgConfig imgConfig = new ImgConfig();
        BeanUtils.copyProperties(addReq, imgConfig);
        add(imgConfig);

        List<ImgConfigCategoryAddReq> categoryAddReqList = addReq.getCategoryList();

        for(int i=0;i<categoryAddReqList.size();i++){
            ImgConfigCategoryAddReq categoryAddReq = categoryAddReqList.get(i);
            ImgCategory imgCategory = new ImgCategory();
            BeanUtils.copyProperties(categoryAddReq, imgCategory);
            imgCategory.setConfigId(imgConfig.getId());
            imgCategoryService.add(imgCategory);

            List<ImgConfigCategoryAddReq> subCategoryList = categoryAddReq.getSubList();

            for(int j=0;j<subCategoryList.size();j++){
                ImgConfigCategoryAddReq subCategoryAddReq = subCategoryList.get(j);
                ImgCategory subCategory = imgCategoryService.getById(subCategoryAddReq.getId());
                BeanUtils.copyProperties(subCategoryAddReq, subCategory);
                subCategory.setPid(imgCategory.getId());
                imgCategoryService.add(subCategory);

                List<ImgConditionAddReq> conditions = subCategoryAddReq.getConditionList();
                for(int k=0;k<conditions.size();k++){
                    ImgConditionAddReq conditionAddReq = conditions.get(k);
                    ImgCondition condition = new ImgCondition();
                    BeanUtils.copyProperties(conditionAddReq, condition);
                    condition.setCategoryId(subCategoryAddReq.getId());
                    imgConditionService.add(condition);
                }
            }
        }
    }

    @Transactional
    public void removeCondition() {
        LambdaQueryWrapper<ImgConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImgConfig::getTargetCompanyId, 0L);
        ImgConfig imgConfig = baseDao.getOne(queryWrapper);
        if (imgConfig!=null){
            List<ImgCategory> categories = imgCategoryService.listByConfigId(imgConfig.getId());
            categories.forEach(t->{
                List<ImgCategory> subList = imgCategoryService.listByPid(t.getId());
                imgConditionService.removeByCategoryIds(subList.stream().map(BaseEntity::getId).collect(Collectors.toList()));
                //imgCategoryService.remove(subList.stream().map(BaseEntity::getId).collect(Collectors.toList()));
            });

            //imgCategoryService.removeByConfigId(imgConfig.getId());
            //baseDao.removeById(imgConfig.getId());
        }
    }

    public void compute(){
        List<ImgConfig> imgConfigs = list();
        for(int i=0;i<imgConfigs.size();i++){
            ImgConfig imgConfig = imgConfigs.get(i);
            ImgConfigVo configVo = getInfo(imgConfig.getId());
            if(configVo.getItem().equals("天")){
                imgCategoryService.compute(configVo);
            }else if(configVo.getItem().equals("月")){
                LocalDate today = LocalDate.now();
                int day =today.getDayOfMonth();
                if(day==1){
                    imgCategoryService.compute(configVo);
                }

            }if(configVo.getItem().equals("季度")){
                LocalDate today = LocalDate.now();
                LocalDate firstDayOfQuarter = today.with(TemporalAdjusters.firstDayOfNextMonth())
                        .minusMonths(today.getMonthValue() % 3)
                        .with(TemporalAdjusters.firstDayOfMonth());

                boolean isFirstDayOfQuarter = today.equals(firstDayOfQuarter);
                if(isFirstDayOfQuarter){
                    imgCategoryService.compute(configVo);
                }

            }

        }
    }

}
